import {
  EditFilled
} from '@ant-design/icons';
import { Descriptions, Card, Tooltip, Button, Divider, Modal } from 'antd';
import { connect } from 'umi';
import React, { useRef, useState } from 'react';
import { history } from 'umi';
import { GridContent } from '@ant-design/pro-layout';
import moment from 'moment';
import Constant from '@/config/contanst'
import { HasPermission } from '@/components/AuthComponent/HasPermission';
import { PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import { queryVipBindCard, memberCardActivate } from './service';
import db from '@/utils/localstorage';
const AuthEdit = HasPermission(EditFilled);
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);
const Info = props => {
  const actionRef = useRef();
  const { currentVip } = props
  const [visible, setVisible] = useState(false);
  const [bindingCardRecord, setBindingCardRecord] = useState({});
  const [dictTypeList, setDictTypeList] = useState(db.get("dictTypeList")['payment_method']);
  const columns = [
    {
      title: '会员卡名称',
      dataIndex: 'cardName',
      hideInSearch: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      hideInSearch: true,
    },
    {
      title: '余额',
      dataIndex: 'balance',
      hideInSearch: true,
      render: (text, record) => record.cardType == '1' ? <span>{text}元</span> :
        record.cardType == '2' ? <Tooltip placement="top" title="永久有效">{text}次</Tooltip> :
          record.cardType == '3' ? <Tooltip placement="top" title={`到期时间${record.periodValidity}`}>{text}天</Tooltip> : ""
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        1: {
          text: '正常',
          status: 'Warning',
        },
        2: {
          text: '永久停卡',
          status: 'Error',
        },
        3: {
          text: '临时停卡',
          status: 'Error',
        },
        4: {
          text: '已失效',
          status: 'Error',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <AuthButton auth={[`vip:card:detail`]} type="link" onClick={() => go2Detail(record)}>详情</AuthButton>
          {
            record.status == '1' && <>
              <AuthDivider auth={['vip:card:detail', `vip:bind:card:renew`]} type="vertical"></AuthDivider>
              <AuthButton auth={[`vip:bind:card:renew`]} type="link" onClick={() => go2Renew(record)}>续卡</AuthButton>
            </>
          }
          {
            record.status == '1' && <>
              <AuthDivider auth={['vip:bind:card:renew', `vip:bind:card:deduction`]} type="vertical"></AuthDivider>
              <AuthButton auth={[`vip:bind:card:deduction`]} type="link" onClick={() => go2Deduction(record)}>扣卡</AuthButton>
            </>
          }
          {
            record.status == '1' && <>
              <AuthDivider auth={['vip:bind:card:deduction', `vip:bind:card:stop`]} type="vertical"></AuthDivider>
              <AuthButton auth={[`vip:bind:card:stop`]} type="link" onClick={() => go2Stop(record)}>停卡</AuthButton>
            </>
          }
          {
            (record.status == '2' || record.status == '3') && <>
              <AuthDivider auth={['vip:bind:card:deduction', `vip:bind:card:active`]} type="vertical"></AuthDivider>
              <AuthButton auth={[`vip:bind:card:active`]} type="link" onClick={() => go2Active(record)}>激活卡</AuthButton>
            </>
          }
          {
            (record.status == '1') && <>
              <AuthDivider auth={['vip:bind:card:convert', `vip:bind:card:active`]} type="vertical"></AuthDivider>
              <AuthButton auth={[`vip:bind:card:convert`]} type="link" onClick={() => go2Convert(record)}>次卡转换</AuthButton>
            </>
          }
        </>
      ),
    },
  ];
  /**
   * 去编辑
   * @param {*} async 
   */
  const goToEdit = async => {
    history.push(`/vip/center/update/${props.id}`);
  }

  /**
   * 激活卡
   * @param {*} record 
   */
  const go2Active = (record) => {
    if (record.status == '2') {
      message.warn("永久停卡无法激活")
      return;
    }
    setVisible(true)
    setBindingCardRecord(record)
  }
  /**
   * 详情
   * @param {*} record 
   */
  const go2Detail = (record) => {
    history.push(`/vip/card/detail/${record.cardId}/${record.memberId}`);
  }

  /**
   * 续卡
   * @param {*} record 
   */
  const go2Renew = record => {
    history.push(`/vip/bind-card/renew/${record.cardId}/${record.memberId}`);
  }

  /**
   * 扣卡
   * @param {*} record 
   */
  const go2Deduction = record => {
    history.push(`/vip/bind-card/deduction/${record.cardId}/${record.memberId}`);
  }

  /**
   * 停卡
   * @param {*} record 
   */
  const go2Stop = record => {
    history.push(`/vip/bind-card/stop/${record.cardId}/${record.memberId}`);
  }

  const go2Convert = record => {
    history.push(`/vip/bind-card/convert/${record.cardId}/${record.memberId}`);
  }
  /**
   * 确认激活
   */
  const handleAddOk = async () => {
    const fieldsValue = await form.validateFields();
    const hide = message.loading('正在激活');
    try {
      let result = await memberCardActivate({
        cardId: bindingCardRecord.cardId,
        memberId: bindingCardRecord.memberId,
        cardType: bindingCardRecord.cardType,
        ...fieldsValue
      });
      hide();
      if (result.code == 0) {
        message.success('激活成功，即将刷新');
        handleCancel();
        actionRef.current.reload()
        return true;
      } else {
        message.warn(result.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('激活失败，请重试');
      return false;
    }
  }

  /**
   * 取消激活
   */
  const handleCancel = () => {
    form.resetFields();
    setVisible(false)
    setBindingCardRecord({})
  }

  /**
 * 跳转新增页
 * @param {*} record 
 */
  const goToSave = async => {
    history.push(`/vip/bind-card/save`);
  }

  return (
    <GridContent>
      <Card
        title="绑卡信息"
        style={{
          marginBottom: 24,
        }}
        bordered={false}
      >
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          search={false}
          options={false}
          request={params => {
            let _params = {
              pageNum: params.current,
              pageSize:1000,
              memberId:props.id,
              ...params,
            }
            delete _params.current
            return queryVipBindCard(_params)
          }}
          postData={result => result.list}
          columns={columns}
          pagination={false}
        />
      </Card>
      <Card
        title="详细信息"
        style={{
          marginBottom: 24,
        }}
        bordered={false}
        extra={<Tooltip placement="top" title="编辑会员"><AuthEdit auth={[`vip:update`]} onClick={() => goToEdit()} /></Tooltip>}
      >
        <Descriptions
          style={{
            marginBottom: 24,
          }}
        >
          <Descriptions.Item label="姓名">{currentVip.name || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="昵称">{currentVip.nickname || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="性别">{currentVip.sex == '1' ? '男' : currentVip.sex == '2' ? '女' : '未知'}</Descriptions.Item>
          <Descriptions.Item label="电话">{currentVip.phone || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="状态">{currentVip.status == '1' ? '正常' : currentVip.status == '2' ? '暂停' : '未知'}</Descriptions.Item>
          <Descriptions.Item label="销售">{currentVip.salesName || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="教练">{currentVip.coachName || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="身高">{currentVip.height || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="身高">{currentVip.weight || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="积分">{currentVip.integralBalance || 0}</Descriptions.Item>
          <Descriptions.Item label="婚姻">{currentVip.isMarriage == '1' ? '已婚' : currentVip.isMarriage == '2' ? '未婚' : '未知'}</Descriptions.Item>
          <Descriptions.Item label="生育">{currentVip.isFertility == '1' ? '已生育' : currentVip.isMarriage == '2' ? '未生育' : '未知'}</Descriptions.Item>
          {/* <Descriptions.Item label="绑定会员卡">3321944288191034921</Descriptions.Item> */}
          <Descriptions.Item label="身份证号">{currentVip.idCard || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="生日">{currentVip.birthday ? moment(currentVip.birthday).format('YYYY-MM-DD') : "未设置"}</Descriptions.Item>
          <Descriptions.Item label="宝宝生日">{currentVip.babybirthday ? moment(currentVip.babybirthday).format('YYYY-MM-DD') : "未设置"}</Descriptions.Item>
          <Descriptions.Item label="来源">{Constant.MemberSourceMap[currentVip.source] || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="家庭地址">{currentVip.homeAddress || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="工作地址">{currentVip.workAddress || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="病史说明">{currentVip.medicalHistoryDescription || '未设置'}</Descriptions.Item>
          <Descriptions.Item label="备注">{currentVip.bz || '未设置'}</Descriptions.Item>
        </Descriptions>
      </Card>
      {
        visible && <Modal
          title="激活卡"
          visible={visible}
          onOk={handleAddOk}
          onCancel={handleCancel}
        >
          <Form
            style={{
              marginTop: 8,
            }}
            form={form}
            name="basic"
          >
            <Form.Item
              {...formItemLayout}
              label="收费"
              name="money"
              rules={[{ required: true, message: '请输入收费金额' }]}
            >
              <InputNumber
                min={0}
                style={{ width: '100%' }}
                formatter={value => `${value}元`}
                parser={value => value.replace('元', '')}
              />
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="支付方式"
              name="paymentMethod"
              rules={[{ required: true, message: '请选择支付方式' }]}
            >
              <Select style={{ width: '100%' }} placeholder="请选择">
                {
                  dictTypeList && dictTypeList.map((item, index) => <Select.Option key={index} value={item.value}>{item.label}</Select.Option>)
                }
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      }
    </GridContent>
  );
};

export default connect(({ }) => ({
}))(Info);
